/*
 * (c) 2012 Leonid Bensman, lbensman.cs00@gtalumni.org
 */
using System;
using System.Collections.Generic;
using System.Text;

namespace CalcSig.Serializers
{
    public interface IHashSerializer { };

    public abstract class HashSerializer<ItemExtendedHash> : IHashSerializer
        where ItemExtendedHash : ItemHash
    {
        private ItemCalculatedDelegate ItemCalculatedDelegate;

        public HashSerializer(IHashCalculator hashCalculator)
        {
            hashCalculator.ItemCalculated += new ItemCalculatedDelegate(OnItemCalculated);
        }

        private void OnItemCalculated(ItemHash itemHash)
        {
            OnItemCalculated(itemHash as ItemExtendedHash);
        }

        protected abstract void OnItemCalculated(ItemExtendedHash itemHash);

        public static string HashAsString(byte[] hash)
        {
            if (hash == null)
            {
                return string.Empty;
            }

            StringBuilder sb = new StringBuilder(hash.Length * 2);

            foreach (byte b in hash)
            {
                sb.Append(string.Format("{0:X2}", b));
            }

            return sb.ToString();
        }

        public static byte[] HashFromString(string hash)
        {
            if (string.IsNullOrEmpty(hash))
            {
                throw new ArgumentNullException("hash");
            }

            if (hash.Length % 2 != 0)
            {
                throw new ArgumentException("Length is not Mod2", "hash");
            }

            byte[] bytes = new byte[hash.Length / 2];

            for (int i = 0; i < bytes.Length; i++)
            {
                bytes[i] = byte.Parse(hash.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);
            }

            return bytes;
        }

    }
}
